import { ref } from "vue";

// 判断当前运行环境
const isApp = () => {
  // #ifdef APP-PLUS
  return true;
  // #endif
  return false;
};

const isH5 = () => {
  // #ifdef H5
  return true;
  // #endif
  return false;
};

// 后端API基础URL
let BASE_URL = "";

// 根据环境动态设置BASE_URL
if (isApp()) {
  BASE_URL = "https://fishpi.cn";
} else if (isH5()) {
  BASE_URL = "/api/";
} else {
  BASE_URL = "https://fishpi.cn";
}

// API密钥存储键名
const API_KEY_STORAGE = "fishpi_api_key";

// 获取存储的API密钥
export const getApiKey = () => {
  return uni.getStorageSync(API_KEY_STORAGE) || "";
};

// 设置API密钥到本地存储
export const setApiKey = (apiKey) => {
  uni.setStorageSync(API_KEY_STORAGE, apiKey);
};

// 清除API密钥
export const clearApiKey = () => {
  uni.removeStorageSync(API_KEY_STORAGE);
};

// 判断用户是否已登录
export const isLoggedIn = () => {
  return !!getApiKey();
};

// 通用请求方法
export const request = (url, method = "GET", data = {}, needApiKey = true) => {
  // 如果需要API密钥且用户未登录，自动跳转到登录页
  if (needApiKey && !isLoggedIn()) {
    uni.navigateTo({
      url: "/pages/login/login",
    });
    return Promise.reject(new Error("未登录"));
  }

  // 构建完整的URL
  const fullUrl = `${BASE_URL}${url}`;

  // 构建请求参数
  const requestData = {
    ...data,
    ...(needApiKey && isLoggedIn() ? { apiKey: getApiKey() } : {}),
  };

  return new Promise((resolve, reject) => {
    uni.request({
      url: fullUrl,
      method,
      data: requestData,
      header: {
        "Content-Type": "application/json",
      },
      success: (res) => {
        // 检查API密钥是否有效或请求失败
        if (res.statusCode === 404) {
          reject(new Error("请求的资源不存在，请检查API路径或网络设置"));
        } else if (res.data.code === -1) {
          if (res.data.msg === "Invalid API Key") {
            clearApiKey();
            uni.navigateTo({
              url: "/pages/login/login",
            });
          }
          reject(new Error(res.data.msg || "请求失败"));
        } else {
          resolve(res.data);
        }
      },
      fail: (err) => {
        console.error("请求失败:", err);
        reject(err);
      },
    });
  });
};

// 为了保持与原有代码的兼容性，导出一个空对象
export default {};
